import logging
import random

from django.http import HttpResponse
from django.shortcuts import render
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from django_redis import get_redis_connection

# Create your views here.
from mall.libs.captcha.captcha import captcha
from mall.utils.yuntongxun.sms import CCP
from . import constants
from .serializers import ImageCodeCheckSerializer
from celery_tasks.sms import tasks as sms_tasks

logger = logging.getLogger("django")


# GET /image_codes/(?P<image_code_id>[\w-]+)/
class ImageCodeView(APIView):
    """图片验证码"""

    def get(self, request, image_code_id):
        """获取图片验证码"""
        # 生成验证码图片
        text, image = captcha.generate_captcha()

        redis_conn = get_redis_connection("verify_codes")
        redis_conn.setex("img_%s" % image_code_id,
                         constants.IMAGE_CODE_REDIS_EXPIRES, text)
        # 固定返回图片验证码数据，不许rest_framework框架的Respons，直接原生HttpRespon即可
        return HttpResponse(image, content_type="image/jpg")


# GET /sms_codes/(?P<mobile>1[3-9]\d{9})/?image_code_id=xxx&text=xxx
class SMSCodeView(GenericAPIView):
    """短信验证码"""
    serializer_class = ImageCodeCheckSerializer

    def get(self, request, mobile):
        """创建短信验证码"""
        # 判断验证码是否在60s内
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        # 生成短信验证码
        sms_code = "%06d" % random.randint(0, 999999)

        # 保存短信验证码和发送记录
        redis_conn = get_redis_connection("verify_codes")
        # redis管道
        pl = redis_conn.pipeline()
        pl.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex("send_flag_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        # 管道通知redis执行命令
        pl.execute()

        # 发送短信验证码
        # try:
        #     expires = constants.SMS_CODE_REDIS_EXPIRES // 60
        #     ccp = CCP()
        #     result = ccp.send_template_sms(mobile, [sms_code, expires],
        # constants.SMS_CODE_TEMP_ID)
        # except Exception as e:
        #     logger.error("发送短信验证码【异常】[mobile: %s]" % mobile)
        #     return Response({"message": "failed"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        # else:
        #     if result == 0:
        #         logger.info("发送验证码短信【正常】, [mobile: %s]" % mobile)
        #         return Response({"message": "OK"})
        #     else:
        #         logger.warning("发送验证码短信【失败】[mobile: %s]" % mobile)
        #         return Response({"message": "failed"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        # 使用celery发送短信验证码
        expires = constants.SMS_CODE_REDIS_EXPIRES // 60
        sms_tasks.send_sms_code.delay(mobile, sms_code, expires)

        return Response({"message": "OK"})







